<script>
import Header from "@/views/Components/Header/header.vue"
import Header4 from "@/views/Components/Header/header4.vue"
import Footer from "@/views/Components/Footer/footer.vue";
import {debounce} from "@/utils/statice";
import {userGetAllAddressService} from "@/api/user/UserService";
export default {
    components: {
        Header,
        Header4,
        Footer
    },
    data() {
        return {
            currentAddress: {},
            addressList: [],
            CartList: [],
            ItemsList: [],
            totalPrice: 0,
            moveCost: 10.00,
            dialogVisible: false,
        };
    },
    computed: {},
    watch: {},
    methods: {
        async InitUserAddresses() {
            let result = await userGetAllAddressService();
            if(result.code === 200) {
                this.addressList = result.data;
                if(result.data.length === 0) {
                    this.$message({
                        message: "请先添加地址,即将跳转到个人中心的地址界面",
                        type: "warning",
                    })
                    setTimeout(() => {
                        this.$router.push({
                            path: "/userAddress"
                        })
                    }, 1000)
                } else {
                    // 确定默认地址
                    result.data.forEach(item => {
                        if(item.defaultValue) {
                            this.currentAddress = item;
                        }
                    })
                }
            } else {
                this.$message({
                    message: "获取用户地址失败,请检查网络状态",
                    type: "error",
                })
            }
        },
        /**
         * 节流函数,改变购物车商品数量
         */
        handleChange: debounce(function (id , num) {
            console.log("商品id: " + id);
            console.log("商品数量: " + num);
            this.updateCart(id, num); // 执行修改
        }, 1000),
        openBtn() {
            this.dialogVisible = true;
        },
        async closeBtn() {
            this.dialogVisible = false;
            await this.InitUserAddresses();
        },
        // 选中要修改的地址
        choseDefaultAdd(val) {
            console.log(val);
            val.defaultValue = true;
            this.addressList.forEach((item) => {
                if (item.id !== val.id) {
                    item.defaultValue = false;
                }
            });
            this.currentAddress = val;
        },
        /**
         * 提交订单
         */
        submitOrder: debounce(function () {
            console.log("创建订单");
            let orderItemCreateDTO = [];
            this.ItemsList.forEach(item => {
                orderItemCreateDTO.push({
                    bookId: item.bookId,
                    num: item.num
                })
            })
            const params = {
                orderItemCreateDTO: orderItemCreateDTO,
                receiveAddress: this.currentAddress.urbanAddr + this.currentAddress.detailAddr,
                receivePhone: this.currentAddress.phone,
                receiveUsername: this.currentAddress.receiverName,
            }
            console.log(JSON.stringify(params));
            fetch("http://localhost:3310/order", {
                method: "POST",
                headers: {
                    "Authorization": this.$store.getters.token,
                    "Content-Type": "application/json",
                },
                body: JSON.stringify(params),
            })
                .then(res => res.json())
                .then(result => {
                    console.log(result);
                    if(result.code === 200) {
                        this.$notify({
                            title: "成功",
                            message: "下单成功！",
                            type: "success",
                        });
                        sessionStorage.setItem(
                            "orderId",
                            JSON.stringify(result.data.orderId)
                        );
                        this.$router.push({path: "/orderSuccess"})
                    } else {
                        this.$notify.error({
                            title: "错误",
                            message: result.message,
                        });
                    }
                })
        }, 100)
    },
    created() {
        this.ItemsList = JSON.parse(sessionStorage.getItem("selectItems"));
        let tol = 0;
        this.ItemsList.forEach(item => {
            tol += item.price * item.num;
        })
        this.totalPrice = tol;
        console.log(this.ItemsList);
        this.InitUserAddresses();
        console.log(this.currentAddress)
    },
    mounted() {
    
    },
}
</script>
<template>
    <div id="confirmOrder">
        <Header />
        <Header4 />
        <el-dialog title="修改地址" :visible.sync="dialogVisible" width="60%">
            <div style="height: 350px;overflow:auto">
                <el-row :gutter="20">
                    <el-col :span="12" v-for="item in addressList" :key="item.id">
                        <el-card shadow="hover" :style="{'color':item.defaultValue?'#67c23a':''}" @click.native="choseDefaultAdd(item)">
                            <div>姓名：{{ item.receiverName }}</div>
                            <div>电话：{{ item.phone }}</div>
                            <div :title="item.urbanAddr+item.detailAddr ">地址：{{ item.urbanAddr }}{{ item.detailAddr }}</div>
                        </el-card>
                    </el-col>
                </el-row>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button size="small" @click="closeBtn">取 消</el-button>
                <el-button size="small" type="primary" @click="dialogVisible = false">确 定</el-button>
            </span>
        </el-dialog>
        <div class="contain">
            <div class="c_address1">
                <div class="title">
                    <div class="tl">收货地址</div>
                    <button class="addAddress" @click="openBtn">
                        修改收货地址
                    </button>
                </div>
                <div class="urls">
                    <div class="urlBox U1 checkBox" v-if="currentAddress != null">
                        <div class="D1">收件人：{{ currentAddress.receiverName }}</div>
                        <div class="D2">联系电话：{{ currentAddress.phone }}</div>
                        <div class="D3">收货地址：{{ currentAddress.urbanAddr }}{{ currentAddress.detailAddr }}</div>
                        <el-tag type="danger" >默认地址</el-tag>
                    </div>
                    <div v-else class="D5">
                        当前没有设置默认地址,请选择
                    </div>
                </div>
            </div>
            <div class="buyItems">
                <div class="buyBody">
                    <div class="ItemBox">
                        <div class="ITEM" v-for="(item, index) in ItemsList" :key="item.bookId">
                            <div class="pic">
                                <el-image :src="item.cover" alt/>
                            </div>
                            <div class="info">{{ item.name }}</div>
                            <div class="num">x {{ item.num }}</div>
                            <div class="total">￥ {{ (item.num * item.price).toFixed(2) }}</div>
                        </div>
                        
                        <div class="Invoice">
                            <div class="In_t">
                                <span>发票信息</span>
                                <span>注：如果商品由第三方卖家销售，则发票由第三方卖家开具。</span>
                            </div>
                            <div class="In_b">
                                <span>电子普通发票</span>
                                <span>个人</span>
                                <a href="#">修改</a>
                            </div>
                        </div>
                    </div>
                    <div class="PriceTotal">
                        <div class="TotalTop">
                            <div class="top">
                                <span>商品由</span>
                                <span>华为商城</span>
                                <span>选择合作快递</span>
                            </div>
                            <div class="bot">
                                <div class="FLAG">
                                    <div></div>
                                </div>
                                <span>标准配送</span>
                            </div>
                        </div>
                        <div class="PriceInfo">
                            <div class="infoL">
                                <div>商品总金额：</div>
                                <div>运费：</div>
                                <div>优惠金额：</div>
                                <div>积分：</div>
                                <div>结算金额：</div>
                            </div>
                            <div class="infoR">
                                <div>￥{{ totalPrice.toFixed(2) }}</div>
                                <div>￥{{ moveCost.toFixed(2) }}</div>
                                <div>
                                    <span style="font-weight: 800;margin-right: -2px;">-</span>
                                    ￥0.00
                                </div>
                                <div>
                                    <span style="font-weight: 800;margin-right: -2px;">-</span>
                                    ￥0.00
                                </div>
                                <div class="money">￥{{ (totalPrice - moveCost).toFixed(2) }}</div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="submitForm">
                    <div class="formContent">
                        <div class="one">
                            <span>应付金额:</span>
                            <span>￥{{ (totalPrice - moveCost).toFixed(2) }}</span>
                        </div>
                        <div class="two">
                            <div class="two_one">
                                <span>配送至:</span>
                                <span>{{ currentAddress.urbanAddr }}{{ currentAddress.detailAddr }}</span>
                            </div>
                            <span class="two_two">{{ currentAddress.receiverName }} {{ currentAddress.phone }}</span>
                        </div>
                        <div class="three">
                            <button @click="submitOrder">提交订单</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <Footer FHeight="0" PTop1="0" />
    </div>
</template>

<style scoped lang="scss">
@import url(../../assets/css/confirmOrder.css);
</style>
